/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;
import java.util.concurrent.locks.LockSupport;

/**
 * A cancellable asynchronous computation.  This class provides a base
 * implementation of {@link Future}, with methods to start and cancel
 * a computation, query to see if the computation is complete, and
 * retrieve the result of the computation.  The result can only be
 * retrieved when the computation has completed; the {@code get}
 * methods will block if the computation has not yet completed.  Once
 * the computation has completed, the computation cannot be restarted
 * or cancelled (unless the computation is invoked using
 * {@link #runAndReset}).
 *
 * <p>A {@code FutureTask} can be used to wrap a {@link Callable} or
 * {@link Runnable} object.  Because {@code FutureTask} implements
 * {@code Runnable}, a {@code FutureTask} can be submitted to an
 * {@link Executor} for execution.
 *
 * <p>In addition to serving as a standalone class, this class provides
 * {@code protected} functionality that may be useful when creating
 * customized task classes.
 *
 * @since 1.5
 * @author Doug Lea
 * @param <V> The result type returned by this FutureTask's {@code get} methods
 */
public class FutureTask<V> implements RunnableFuture<V> {
    /*
     * Revision notes: This differs from previous versions of this
     * class that relied on AbstractQueuedSynchronizer, mainly to
     * avoid surprising users about retaining interrupt status during
     * cancellation races. Sync control in the current design relies
     * on a "state" field updated via CAS to track completion, along
     * with a simple Treiber stack to hold waiting threads.
     *
     * Style note: As usual, we bypass overhead of using
     * AtomicXFieldUpdaters and instead directly use Unsafe intrinsics.
     */

    /**
     * The run state of this task, initially NEW.  The run state
     * transitions to a terminal state only in methods set,
     * setException, and cancel.  During completion, state may take on
     * transient values of COMPLETING (while outcome is being set) or
     * INTERRUPTING (only while interrupting the runner to satisfy a
     * cancel(true)). Transitions from these intermediate to final
     * states use cheaper ordered/lazy writes because values are unique
     * and cannot be further modified.
     *
     * Possible state transitions:
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED
     */
    //当前任务状态
    private volatile int state;
    //当前任务尚未执行
    private static final int NEW          = 0;
    //当前任务正在结束，尚未完全结束，一种临界状态
    private static final int COMPLETING   = 1;
    //当前任务正常结束
    private static final int NORMAL       = 2;
    //当前任务执行过程中触发异常  内部构造的callable.run()触发了异常
    private static final int EXCEPTIONAL  = 3;
    //当前任务被取消  callable任务
    private static final int CANCELLED    = 4;
    //当前任务中断中。。
    private static final int INTERRUPTING = 5;
    //当前任务已中断
    private static final int INTERRUPTED  = 6;

    /**
     * The underlying callable; nulled out after running
     *
     * submit(runnable/callable)都会封装成callable
     * runnable是使用装饰者模式 伪装成 callable
     */
    private Callable<V> callable;

    /**
     * The result to return or exception to throw from get()
     *
     * 正常情况：任务正常结束，outcome保存返回结果
     * 异常情况：callable抛出异常，结束线程；outcome保存对应的异常结果
     */
    private Object outcome; // non-volatile, protected by state reads/writes

    /**
     * The thread running the callable; CASed during run()
     *
     * 当前任务被执行期间，保存执行当前任务线程对象的引用
     */
    private volatile Thread runner;

    /**
     * Treiber stack of waiting threads
     *
     * 因为可能会有多个线程获取当前任务的结果
     * 所以这里使用了 栈(先进后出)这种数据结构，来保存对应线程
     * 这些等待获取结果的线程都处于等待状态(不会占用CPU，除非有线程unpark、interpret等方式影响线程)
     */
    private volatile WaitNode waiters;

    /**
     * Returns result or throws exception for completed task.
     *
     * @param s completed state value
     *
     * 向外面报告结果的方法
     */
    @SuppressWarnings("unchecked")
    private V report(int s) throws ExecutionException {
        //正常情况下，outcome保存的任务执行之后的结果 或者 执行任务产生的异常
        Object x = outcome;
        //条件成立：当前任务状态正常结束，直接返回结果
        if (s == NORMAL)
            return (V)x;
        //被取消状态，也就是任务在执行过程中被手动取消了，直接抛出一个取消异常
        if (s >= CANCELLED)
            throw new CancellationException();
        //剩下就是任务执行的有问题。这个时候就直接抛出异常
        throw new ExecutionException((Throwable)x);
    }

    /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Callable}.
     *
     * @param  callable the callable task
     * @throws NullPointerException if the callable is null
     */
    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        //我们传入的业务代码，要执行的代码块
        this.callable = callable;
        //状态设置为 new
        this.state = NEW;       // ensure visibility of callable
    }

    /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Runnable}, and arrange that {@code get} will return the
     * given result on successful completion.
     *
     * @param runnable the runnable task
     * @param result the result to return on successful completion. If
     * you don't need a particular result, consider using
     * constructions of the form:
     * {@code Future<?> f = new FutureTask<Void>(runnable, null)}
     * @throws NullPointerException if the runnable is null
     */
    public FutureTask(Runnable runnable, V result) {
        /**
         * 你传入的是什么，返回的就是什么
         * 因为这是装饰者模式，它并没有改变你对应的结构
         * 如果是这种方式，返回结果可能是null(因为封装的时候传入的就是null，你自己封装就是你传入的值)或你传入的值
         */
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

    public boolean isCancelled() {
        return state >= CANCELLED;
    }

    public boolean isDone() {
        return state != NEW;
    }

    /**
     * 使用场景：通过线程池，提交任务之后，这个任务执行的太久了，并且他一直没有结束
     *          等待的时间太久了，可以使用获取到的句柄，取消这个任务
     *
     * 取消成功返回true 失败返回false
     */
    public boolean cancel(boolean mayInterruptIfRunning) {
        //条件一：当前 任务处于运行中 或 处于线程池 任务队列中
        //条件二：根据你传入的参数，把当前从 new状态改为中断中 或 已取消； 条件成立说明状态修改成功
        if (!(state == NEW &&
              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;

        //尝试中断任务
        try {    // in case call to interrupt throws exception
            //如果传入的是true,就表示你要给执行当前任务的线程发一个中断信号
            if (mayInterruptIfRunning) {
                try {
                    //获取到当前线程
                    Thread t = runner;
                    //当前线程是null的情况是当前任务还在线程池的 任务队列中，还没有执行
                    if (t != null)
                        //尝试中断线程
                        //如果你的任务不是响应中断的，什么都不会发生
                        t.interrupt();
                } finally { // final state
                    //设置任务状态为中断完成
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            //唤醒所有get 阻塞线程
            finishCompletion();
        }
        return true;
    }

    /**
     * 外部线程获取当前任务执行结果的方法
     * 场景：会有多个线程等待当前任务结果的场景
     */
    public V get() throws InterruptedException, ExecutionException {
        //获取当前任务状态
        int s = state;
        //判断当前状态是否出于小于等于 完成中
        if (s <= COMPLETING)
            //如果当前任务还没有完成，那么下面这个方法就会一直阻塞
            //也就是说，其他调用get方法的外部线程全部会被下面这个方法阻塞，也会被释放
            //s就是获取到的当前任务的状态
            s = awaitDone(false, 0L);
        //向外面去报告结果的方法
        return report(s);
    }

    /**
     * 带有超时时间的get方法
     * @throws CancellationException {@inheritDoc}
     */
    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        //时间unit校验
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        //当前状态小于完成中，线程醒来之后状态也是处于完成中，那么抛出异常
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        //向外面去报告结果的方法
        return report(s);
    }

    /**
     * Protected method invoked when this task transitions to state
     * {@code isDone} (whether normally or via cancellation). The
     * default implementation does nothing.  Subclasses may override
     * this method to invoke completion callbacks or perform
     * bookkeeping. Note that you can query status inside the
     * implementation of this method to determine whether this task
     * has been cancelled.
     */
    protected void done() { }

    /**
     * Sets the result of this future to the given value unless
     * this future has already been set or has been cancelled.
     *
     * <p>This method is invoked internally by the {@link #run} method
     * upon successful completion of the computation.
     *
     * 给outcome设置相应的值
     */
    protected void set(V v) {
        //通过CAS的方式，先把当前任务的状态设置为完成中这样的一个临界状态
        //那么这个步骤有没有可能会失败呢？
        //其实是有可能的，在这个执行之前，外部线程等不及了，直接在set执行CAS之前把任务cancel了
        //那么这个时候，task就被取消了，但是这个概率很小
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            //把任务执行后的值，返回给线程
            outcome = v;
            //通过内存的方式，把状态设置会正常状态，这个不是CAS操作
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            //善后工作
            finishCompletion();
        }
    }

    /**
     * Causes this future to report an {@link ExecutionException}
     * with the given throwable as its cause, unless this future has
     * already been set or has been cancelled.
     *
     * <p>This method is invoked internally by the {@link #run} method
     * upon failure of the computation.
     *
     * 在当前任务执行失败之后，会调用这个方法，把捕获到的异常设置到outcome中
     */
    protected void setException(Throwable t) {
        //和set方法一样，通过CAS的操作，先把状态设置为完成中的这样一个临界状态
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            //把捕获到的异常赋值给outcome
            outcome = t;
            //通过内存的方式把当前任务的状态修改为完成状态
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

    /**
     * 线程执行的入口
     * submit(runnable/callable) -> newTaskFor(runnable) -> execute(task) -> pool
     */
    public void run() {
        /**
         * 条件一：状态为new
         * 条件二： !UNSAFE.compareAndSwapObject(this,runnerOffset,null,Thread.currentThread())
         *          通过CAS的方式把当前线程设置到FutureTask的属性 runnerOffset中；设置成功返回true
         *          CAS失败，当前任务被其他线程抢占了
         * 如果不满足上面两个条件就直接跳出去
         */
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        /**
         * 执行到这里
         * 表示 当前任务状态一定为new
         *     并且当前线程也抢占任务成功
         */
        try {
            //封装我们编写的业务代码
            Callable<V> c = callable;
            //条件一：判断传入的任务是否为null，避免在构建任务的时候传入了一个null进来
            //条件二：判断任务是否是new状态，为了避免在这之前任务被cancel掉，被取消
            if (c != null && state == NEW) {
                //保存任务执行后的结果
                V result;
                //任务执行成功 为true
                //任务执行失败，或抛出异常，则为 false
                //如果boolean 不赋值的话，它默认是false
                boolean ran;
                try {
                    //执行我们封装好的任务
                    result = c.call();
                    //设置执行结果
                    ran = true;
                } catch (Throwable ex) {
                    //触发异常，异常处理
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    //任务执行成功，没有发生异常
                    //把执行后的结果返回给outcome
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            //在这个当前这个执行者的这个线程设置为null，也就相当于要把数据清空释放资源的准备
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                //判断当前任务的状态是不是中断以上的这个状态
                handlePossibleCancellationInterrupt(s);
        }
    }

    /**
     * Executes the computation without setting its result, and then
     * resets this future to initial state, failing to do so if the
     * computation encounters an exception or is cancelled.  This is
     * designed for use with tasks that intrinsically execute more
     * than once.
     *
     * @return {@code true} if successfully run and reset
     * 执行并且重置该futureTask
     * 一般用于单个任务多次执行
     */
    protected boolean runAndReset() {
        //当前任务状态为新建状态，并且把执行线程设置为当前线程的情况下可以走下去
        //否则直接返回false
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return false;
        boolean ran = false;
        //获取当前状态
        int s = state;
        try {
            Callable<V> c = callable;
            if (c != null && s == NEW) {
                try {
                    //执行任务，但是不修改状态，并且不设置返回值
                    c.call(); // don't set result
                    ran = true;
                } catch (Throwable ex) {
                    //如果抛出异常，还是会对异常进行处理
                    setException(ex);
                }
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            //执行线程置空
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            //再次获取当前状态
            s = state;
            //任务被中断，执行中断
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
        //当且仅当 任务执行成功 并且任务状态没有被修改的情况下，返回true
        return ran && s == NEW;
    }

    /**
     * Ensures that any interrupt from a possible cancel(true) is only
     * delivered to a task while in run or runAndReset.
     * 打断当前任务执行
     */
    private void handlePossibleCancellationInterrupt(int s) {
        // It is possible for our interrupter to stall before getting a
        // chance to interrupt us.  Let's spin-wait patiently.
        //如果是 中断中 这个状态，那么会一直等待，会一直让执行任务的线程释放CPU
        //直到执行当前任务的状态由中断中变成了已中断
        if (s == INTERRUPTING)
            while (state == INTERRUPTING)
                Thread.yield(); // wait out pending interrupt

        // assert state == INTERRUPTED;

        // We want to clear any interrupt we may have received from
        // cancel(true).  However, it is permissible to use interrupts
        // as an independent mechanism for a task to communicate with
        // its caller, and there is no way to clear only the
        // cancellation interrupt.
        //
        // Thread.interrupted();
    }

    /**
     * Simple linked list nodes to record waiting threads in a Treiber
     * stack.  See other classes such as Phaser and SynchronousQueue
     * for more detailed explanation.
     * 这里存放所有等待该任务结果的所有的线程
     */
    static final class WaitNode {
        volatile Thread thread;
        volatile WaitNode next;
        WaitNode() { thread = Thread.currentThread(); }
    }

    /**
     * Removes and signals all waiting threads, invokes done(), and
     * nulls out callable.
     * 善后工作
     * 把阻塞的线程进行唤醒
     */
    private void finishCompletion() {
        // assert state > COMPLETING;
        //遍历等待栈中所有的线程 q指向等待栈中的头节点
        for (WaitNode q; (q = waiters) != null;) {
            //通过CAS的方式，把头节点置成空
            //为什么需要CAS操作？ 因为会有竞争，其他线程进行cancel当前任务的时候也会调用这个方法
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
                //自旋
                for (;;) {
                    //获取当前节点的线程
                    Thread t = q.thread;
                    //如果当前节点的线程不为空
                    if (t != null) {
                        //先把当前节点的线程置为null
                        q.thread = null;
                        //唤醒当前线程，在哪里阻塞，就会在那里被唤醒
                        LockSupport.unpark(t);
                    }
                    //拿到当前节点的下一个
                    WaitNode next = q.next;
                    //如果当前节点的下一个节点已经是null了，就表示当前节点已经是最后一个节点了
                    if (next == null)
                        break;
                    //把当前节点的下一节点指针置为null 等待gc
                    q.next = null; // unlink to help gc
                    //遍历
                    q = next;
                }
                break;
            }
        }
        //什么都没做，可以自己扩展
        done();
        //将callable任务置为null 等待gc
        callable = null;        // to reduce footprint
    }

    /**
     * Awaits completion or aborts on interrupt or timeout.
     *
     * @param timed true if use timed waits
     * @param nanos time to wait, if timed
     * @return state upon completion
     *
     * 阻塞所有外部调用get方法的线程
     */
    private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        //0L 不带超时， 超时的意思，就是说外部线程会等待或阻塞多久
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        //引用当前线程 封装成 waitNode对象
        WaitNode q = null;
        //表示当前 waitNode对象 有没有入队/压栈
        boolean queued = false;
        //进入自旋
        for (;;) {
            //条件成立：说明当前线程唤醒是被其他线程使用中断来唤醒的
            //Thread.interrupted() 如果线程被中断了就会返回true，如果第二次调用就会返回false了
            if (Thread.interrupted()) {
                //从队列中移除掉这个线程，因为这个线程已经被中断了，当前node出栈
                removeWaiter(q);
                //抛出中断异常
                throw new InterruptedException();
            }

            //条件成立，当前线程是被其他线程使用unpark这样的方式唤醒的，会正常执行

            //拿到当前任务的状态
            int s = state;
            //条件成立：当前任务已经执行完成、或者已经有结果了
            if (s > COMPLETING) {
                //条件成立：已经为当前线程创建过 node了，这个时候需要把 node.thread=null helpGC
                //其实这一步就相当于取消当前线程的休眠
                if (q != null)
                    q.thread = null;
                //直接返回当前状态
                return s;
            }
            //如果当前任务快要完成了，接近完成或失败状态
            else if (s == COMPLETING) // cannot time out yet
                //当前线程释放一下CPU，进入下一次抢占CPU
                Thread.yield();

            //条件成立，第一次自旋，当前线程还未创建waitNode对象，此时为当前线程创建waitNode对象
            else if (q == null)
                //就是直接为当前线程new一个waitNode对象
                q = new WaitNode();

            //第二次自旋，也就是当前线程创建了waitNode对象，但是还没有入队/压栈
            else if (!queued)
                //q.next=waiters 将当前线程node节点，指向原来队列的头节点
                //通过CAS的方式 设置waiters 指向当前 线程node
                //如果成功表示这个线程入栈了，如果失败，其他线程就先你一步入栈了
                //如果这次没有入栈成功，下次还会之自旋到这里直到成功为止
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
            //第三次自旋，会来到这里
            else if (timed) {
                //调用get方法带参数的会来到这里
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                LockSupport.parkNanos(this, nanos);
            }
            else
                //调用get方法无参会来到这里
                //如果没有传入等待时间的话就会来到这里
                //在这里会把当前线程park掉，也就是把线程的状态设置为witting状态，相当于休眠
                //除非有其他线程唤醒/中断
                //当被休眠的线程醒来的时候，还会在这里，进行自旋
                LockSupport.park(this);
        }
    }

    /**
     * Tries to unlink a timed-out or interrupted wait node to avoid
     * accumulating garbage.  Internal nodes are simply unspliced
     * without CAS since it is harmless if they are traversed anyway
     * by releasers.  To avoid effects of unsplicing from already
     * removed nodes, the list is retraversed in case of an apparent
     * race.  This is slow when there are a lot of nodes, but we don't
     * expect lists to be long enough to outweigh higher-overhead
     * schemes.
     * 遍历把需要出栈的node 全部出栈
     */
    private void removeWaiter(WaitNode node) {
        if (node != null) {
            //将栈中，这个节点先置为null，便于排除和查找
            node.thread = null;
            retry:
            for (;;) {          // restart on removeWaiter race
                //遍历当前链表，也就是栈， 条件是节点不为null  执行一次就把当前节点往下移动一下
                // pred: 遍历到的每一个节点，表示当前节点的上一个节点
                // q: 当前节点
                // s: 当前节点的下一个节点
                for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
                    //设置当前节点的下一个节点
                    s = q.next;
                    //如果当前节点的不为null，则把把前一个节点设置为当前
                    //如果这个条件不满足，则表示找到了需要出栈的节点
                    if (q.thread != null)
                        pred = q;
                    //如果前一个节点不为null，表示当前节点不是头节点
                    //但是当前节点为null 也就表示找到对应的节点了
                    else if (pred != null) {
                        //把上一个节点和下一个节点连起来，这样的话，就把需要出栈的节点出栈了
                        pred.next = s;
                        //判断上一个节点是否也需要出栈了，如果也需要出栈的话，就需要重新排栈
                        if (pred.thread == null) // check for race
                            //跳转到retry的地方
                            continue retry;
                    }
                    //当前节点是头节点的处理方式
                    //通过CAS的方式，直接跳过头节点，把头节点的下一个节点变成头节点
                    else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                          q, s))
                        continue retry;
                }
                //当真个队列都没有需要处理的节点的时候退出当前循环
                break;
            }
        }
    }

    // Unsafe mechanics
    private static final sun.misc.Unsafe UNSAFE;
    private static final long stateOffset;
    private static final long runnerOffset;
    private static final long waitersOffset;
    static {
        try {
            UNSAFE = sun.misc.Unsafe.getUnsafe();
            Class<?> k = FutureTask.class;
            stateOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("state"));
            runnerOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("runner"));
            waitersOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("waiters"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }

}
